package com.semac.client.paginas.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.semac.client.aplicacao.AplicacaoController;
import com.semac.client.aplicacao.PaginasController;
import com.semac.client.aplicacao.Pagina;
import com.semac.client.rpc.ServicoAutenticacaoRPC;
import com.semac.client.rpc.ServicoAutenticacaoRPCAsync;
import com.semac.shared.exceptions.AuthenticationException;

public class LoginUI extends Composite implements Pagina{

	private ServicoAutenticacaoRPCAsync servicoAutenticacao = ServicoAutenticacaoRPC.Util.getInstance();
	
	private static LoginUIUiBinder uiBinder = GWT.create(LoginUIUiBinder.class);
	@UiField TextBox loginBox;
	@UiField PasswordTextBox passBox;
	@UiField Button button;
	@UiField Label statusLabel;

	interface LoginUIUiBinder extends UiBinder<Widget, LoginUI> {
	}

	public LoginUI() {
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	@UiHandler("button")
	void onButtonClick(ClickEvent event) {

		this.statusLabel.setText("Verificando login...");		
		
		servicoAutenticacao.fazLogin(this.loginBox.getText(), this.passBox.getText(), new AsyncCallback<Void>() {			
			@Override
			public void onSuccess(Void result) {
				statusLabel.setText("Logado!");
				//para a aplicacao pegar o novo usuario que foi logado na session do servidor
				//e mudar a tela da pagina
				AplicacaoController.getInstance().refresh();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				if (caught instanceof AuthenticationException){
					statusLabel.setText(caught.getMessage());
				}else{
					statusLabel.setText("Falha na comunicacao com o servidor");
				}			
			}
		});
	}

	@Override
	public String getValorHistoryToken() {
		return PaginasController.LOGIN;
	}

	@Override
	public Widget getView() {
		return this;
	}
}
